package com.gpframework.module.controller.wages;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.gpframework.common.annotation.Log;
import com.gpframework.common.core.controller.BaseController;
import com.gpframework.common.core.domain.AjaxResult;
import com.gpframework.common.core.page.TableDataInfo;
import com.gpframework.common.enums.BusinessType;
import com.gpframework.common.enums.YesNoEnum;
import com.gpframework.common.utils.poi.ExcelUtil;
import com.gpframework.module.system.mapper.SysDictDataMapper;
import com.gpframework.module.wages.domain.GzCompletionSalesTasks;
import com.gpframework.module.wages.domain.GzMonthlySalesCommission;
import com.gpframework.module.wages.domain.GzPersonnelFoundation;
import com.gpframework.module.wages.domain.req.GzMonthlySalesCommissionAdd;
import com.gpframework.module.wages.domain.req.GzMonthlySalesCommissionReq;
import com.gpframework.module.wages.domain.req.GzMonthlySalesCommissionUpdate;
import com.gpframework.module.wages.domain.vo.GzMonthlySalesCommissionVo;
import com.gpframework.module.wages.service.IGzCompletionSalesTasksService;
import com.gpframework.module.wages.service.IGzMonthlyReceiptOfGoodsService;
import com.gpframework.module.wages.service.IGzMonthlySalesCommissionService;
import com.gpframework.module.wages.service.IGzPersonnelFoundationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
/**
 * @ClassName GzMonthlySalesCommissionController
 * @Author gpframework
 * @Date 2024-01-24
 * @Version 1.0.0
 * @Description 销售月度提成Controller
 */
@Validated
@Api(tags = "销售月度提成")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@SuppressWarnings({"rawtypes","unchecked"})
@RequestMapping("/wages/monthlysalescommission" )
public class GzMonthlySalesCommissionController extends BaseController {

    private final IGzMonthlySalesCommissionService iGzMonthlySalesCommissionService;
    private final IGzPersonnelFoundationService iGzPersonnelFoundationService;

    //收货月度
    private final IGzMonthlyReceiptOfGoodsService iGzMonthlyReceiptOfGoodsService;

   //年度完成任务(销售任务)
    private final IGzCompletionSalesTasksService iGzCompletionSalesTasksService;



    private final SysDictDataMapper sysDictDataMapper;

    @ApiOperation("评定是否完成")
    @GetMapping("/assessCompleted")
    public AjaxResult assessCompleted(@JsonFormat(pattern = "yyyy-MM") Date month , String deptName) {

        List<GzMonthlySalesCommission> gzMonthlySalesCommissionList = iGzMonthlySalesCommissionService.list(new QueryWrapper<GzMonthlySalesCommission>()
                .eq("month", month)
                .or()
                .eq("department_name", deptName)
                .isNotNull("monthly_total_sales")
                .eq("del_status", YesNoEnum.NO.getKey()));

        for (GzMonthlySalesCommission gzMonthlySalesCommission : gzMonthlySalesCommissionList) {
            GzCompletionSalesTasks completionSalesTasks = iGzCompletionSalesTasksService.getOne(new LambdaQueryWrapper<GzCompletionSalesTasks>()
                    .eq(GzCompletionSalesTasks::getMonth, gzMonthlySalesCommission.getMonth())
                    .eq(GzCompletionSalesTasks::getUserId, gzMonthlySalesCommission.getUserId())
                    .isNotNull(GzCompletionSalesTasks::getTargetSales)
                    //.le(GzCompletionSalesTasks::getTargetSales, gzMonthlySalesCommission.getMonthlyTotalSales())
                    .eq(GzCompletionSalesTasks::getDelStatus, YesNoEnum.NO.getKey()));
            if (completionSalesTasks != null && gzMonthlySalesCommission.getMonthlyTotalSales().compareTo(completionSalesTasks.getTargetSales())>=0){
                // 月度总销售 大于等于  目标销售 设置为完成 状态
                gzMonthlySalesCommission.setComplete(1);
            }else {
                gzMonthlySalesCommission.setComplete(0);
            }
            if (completionSalesTasks==null){
                gzMonthlySalesCommission.setComplete(2);
            }

        }
        return AjaxResult.success(iGzMonthlySalesCommissionService.updateBatchById(gzMonthlySalesCommissionList)?1:0);


    }

 /**
  * @Description 分页
  * @Author gpframework
  * @Date 2024-01-24
  * @Param gzMonthlySalesCommission
  * @Return TableDataInfo
 */
    @ApiOperation("列表")
    //@PreAuthorize("@ss.hasPermi('wages:monthlysalescommission:list')")
    @GetMapping("/list")
    public TableDataInfo<GzMonthlySalesCommissionVo> list(GzMonthlySalesCommissionReq gzMonthlySalesCommissionReq)
    {
        startPage();
        QueryWrapper<GzMonthlySalesCommission> lqw = new QueryWrapper<GzMonthlySalesCommission>();
        gzMonthlySalesCommissionReq.generatorQuery(lqw,true);
        //lqw.isNotNull("rating_ievel");
        lqw.ne("department_name","办公室");
        List<GzMonthlySalesCommissionVo> list = iGzMonthlySalesCommissionService.listVo(lqw);
        return getDataTable(list);
    }

    @ApiOperation("销售月度提成汇总")
    //@PreAuthorize("@ss.hasPermi('wages:monthlysalescommission:list')")
    @GetMapping("/listed")
    public TableDataInfo<GzMonthlySalesCommissionVo> listed(GzMonthlySalesCommissionReq gzMonthlySalesCommissionReq)
    {
        startPage();
        QueryWrapper<GzMonthlySalesCommission> lqw = new QueryWrapper<GzMonthlySalesCommission>();
        gzMonthlySalesCommissionReq.generatorQuery(lqw,true);
        //lqw.isNotNull("rating_ievel");
        lqw.ne("department_name","办公室");
        List<GzMonthlySalesCommissionVo> list = iGzMonthlySalesCommissionService.listVoed(lqw);
        return getDataTable(list);
    }
    /**
     * @Description 新增
     * @Author gpframework
     * @Date 2024-01-24
     * @Param gzMonthlySalesCommission
     * @Return TableDataInfo
     */
    @ApiOperation("新增")
    //@PreAuthorize("@ss.hasPermi('wages:monthlysalescommission:add')" )
    @Log(title = "添加销售月度提成" , businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Valid @RequestBody GzMonthlySalesCommissionAdd gzMonthlySalesCommissionAdd) {
        GzMonthlySalesCommission gzMonthlySalesCommission = Convert.convert(new TypeReference<GzMonthlySalesCommission>() {}, gzMonthlySalesCommissionAdd);
        return toAjax(iGzMonthlySalesCommissionService.save(gzMonthlySalesCommission) ? 1 : 0);
    }

    /**
     * @Description 修改
     * @Author gpframework
     * @Date 2024-01-24
     * @Param gzMonthlySalesCommission
     * @Return TableDataInfo
     */
    @ApiOperation("修改")
    //@PreAuthorize("@ss.hasPermi('wages:monthlysalescommission:edit')" )
    @Log(title = "修改销售月度提成" , businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Valid @RequestBody GzMonthlySalesCommissionUpdate gzMonthlySalesCommissionUpdate) {
        for (GzMonthlySalesCommissionUpdate monthlySalesCommissionUpdate : gzMonthlySalesCommissionUpdate.getGzMonthlySalesCommissionList()) {
            GzMonthlySalesCommission gzMonthlySalesCommission = Convert.convert(new TypeReference<GzMonthlySalesCommission>() {
            }, monthlySalesCommissionUpdate);


            BigDecimal result = ((monthlySalesCommissionUpdate.getMonthlyTotalSales().subtract(monthlySalesCommissionUpdate.getStartingPointTaxation())).divide(BigDecimal.valueOf(100000))).add(BigDecimal.ONE);

            gzMonthlySalesCommission.setSalesLevel(result);
            iGzMonthlySalesCommissionService.updateById(gzMonthlySalesCommission);
        }

        return toAjax(true);
    }


    /**
     * @Description 导出
     * @Author gpframework
     * @Date 2024-01-24
     * @Param gzMonthlySalesCommission
     * @Return TableDataInfo
     */

    @PreAuthorize("@ss.hasPermi('wages:monthlysalescommission:export')" )
    @Log(title = "导出销售月度提成" , businessType = BusinessType.EXPORT)
    @GetMapping("/export" )
    public AjaxResult export(GzMonthlySalesCommissionReq gzMonthlySalesCommissionReq) {
        QueryWrapper<GzMonthlySalesCommission> lqw = new QueryWrapper<GzMonthlySalesCommission>();
        gzMonthlySalesCommissionReq.generatorQuery(lqw,true);
        //lqw.isNotNull("rating_ievel");
        lqw.ne("department_name","办公室");
        List<GzMonthlySalesCommissionVo> list = iGzMonthlySalesCommissionService.listVo(lqw);
        ExcelUtil<GzMonthlySalesCommissionVo> util = new ExcelUtil<GzMonthlySalesCommissionVo>(GzMonthlySalesCommissionVo. class);
        return util.exportExcel(list, "monthlysalescommission" );
    }

    @ApiOperation("导入销售月度有提示")
    @PreAuthorize("@ss.hasPermi('wages:personnelfoundation:add')")
    @Log(title = "导入销售月度有提示", businessType = BusinessType.INSERT)
    @PostMapping("/import")
    public AjaxResult importListNote(MultipartFile file, boolean updateSupport) throws Exception {
        if (file == null) {
            return AjaxResult.error("获取不到导入文件");
        }
        boolean excel = ExcelUtil.isExcel(file.getOriginalFilename());
        if (!excel) {
            return AjaxResult.error("导入文件格式错误，请导入excel文件");
        }

        // 导入新数据
        ExcelUtil<GzMonthlySalesCommissionVo> util = new ExcelUtil<GzMonthlySalesCommissionVo>(GzMonthlySalesCommissionVo.class);
        List<GzMonthlySalesCommissionVo> excelList = util.importCacheExcel(file.getInputStream());

        String message = iGzMonthlySalesCommissionService.importListNote(excelList, updateSupport);
        return AjaxResult.success(message);
    }



    @ApiOperation("导入销售月度")
    //@PreAuthorize("@ss.hasPermi('manufacture:employeeevaluation:add')" )
    @Log(title = "导入销售月度" , businessType = BusinessType.INSERT)
    //@PostMapping("/import")
    @Transactional
    public AjaxResult importList(MultipartFile file) throws Exception {
        if (file == null) {
            return AjaxResult.error("获取不到导入文件");
        }
        boolean excel = ExcelUtil.isExcel(file.getOriginalFilename());
        if (!excel) {
            return AjaxResult.error("导入文件格式错误，请导入excel文件");
        }
        // 导入新数据
        ExcelUtil<GzMonthlySalesCommissionVo> util = new ExcelUtil<GzMonthlySalesCommissionVo>(GzMonthlySalesCommissionVo.class);
        List<GzMonthlySalesCommissionVo> excelList = util.importCacheExcel(file.getInputStream());
        List<GzMonthlySalesCommission> list = Convert.convert(new TypeReference<List<GzMonthlySalesCommission>>() {}, excelList);

        for (int i = 0; i < list.size(); i++) {
            GzPersonnelFoundation gzPersonnelFoundation = iGzPersonnelFoundationService.getOne(new QueryWrapper<GzPersonnelFoundation>()
                    .eq("name", list.get(i).getName())
                    .eq("department_name", list.get(i).getDepartmentName())
                    .eq("del_status", YesNoEnum.NO.getKey()));


            GzMonthlySalesCommission gzMonthlySalesCommission = iGzMonthlySalesCommissionService.getOne(new QueryWrapper<GzMonthlySalesCommission>()
                    .eq("name", list.get(i).getName())
                    .eq("department_name", list.get(i).getDepartmentName())
                    .eq("month", list.get(i).getMonth())
                    .eq("del_status", YesNoEnum.NO.getKey()));
            if (!StringUtils.isEmpty(gzMonthlySalesCommission))
            {
                list.get(i).setId(gzMonthlySalesCommission.getId());
                //默认为待评定状态
                list.get(i).setComplete(2);
            }

            list.get(i).setUserId(gzPersonnelFoundation.getId());
            //默认为待评定状态
            list.get(i).setComplete(2);
        }

        return iGzMonthlySalesCommissionService.saveOrUpdateBatch(list) ? AjaxResult.success("导入成功") : AjaxResult.error();
    }


    /**
     * @Description 详情
     * @Author gpframework
     * @Date 2024-01-24
     * @Param gzMonthlySalesCommission
     * @Return TableDataInfo
     */
    @ApiOperation("详情")
    //@PreAuthorize("@ss.hasPermi('wages:monthlysalescommission:query')" )
    @GetMapping(value = "/{id}" )
    public AjaxResult<GzMonthlySalesCommissionVo> getInfo(@PathVariable("id" ) Long id) {
        return AjaxResult.success(iGzMonthlySalesCommissionService.getVoById(id));
    }



    /**
     * @Description 删除
     * @Author gpframework
     * @Date 2024-01-24
     * @Param gzMonthlySalesCommission
     * @Return TableDataInfo
     */
    @ApiOperation("删除")
    //@PreAuthorize("@ss.hasPermi('wages:monthlysalescommission:remove')" )
    @Log(title = "删除销售月度提成" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}" )
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(iGzMonthlySalesCommissionService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }


    @ApiOperation("生成销售月度提成")
    //@PreAuthorize("@ss.hasPermi('wages:monthlysalescommission:generateEvaluate')" )
    @Log(title = "生成销售月度提成" , businessType = BusinessType.INSERT)
    @PostMapping("/monthlysalescommission")
    public AjaxResult monthlysalescommission(@RequestBody GzMonthlySalesCommissionReq gzMonthlySalesCommissionReq) throws ParseException {
        List<GzPersonnelFoundation> gzPersonnelFoundations=iGzPersonnelFoundationService.lambdaQuery().eq(GzPersonnelFoundation::getDepartmentType,1)
                .list();
        iGzMonthlySalesCommissionService.remove(new QueryWrapper<GzMonthlySalesCommission>().eq("month", gzMonthlySalesCommissionReq.getMonth()));
        List<GzMonthlySalesCommission> gzMonthlySalesCommissions=new ArrayList<>();
        for (GzPersonnelFoundation gzPersonnelFoundation : gzPersonnelFoundations){
            GzMonthlySalesCommission gzMonthlySalesCommission=new GzMonthlySalesCommission();
            gzMonthlySalesCommission.setMonth(gzMonthlySalesCommissionReq.getMonth());
            gzMonthlySalesCommission.setDepartmentName(gzPersonnelFoundation.getDepartmentName());
            gzMonthlySalesCommission.setUserId(gzPersonnelFoundation.getId());
            gzMonthlySalesCommission.setName(gzPersonnelFoundation.getName());
            //销售档位
            if (StringUtils.isEmpty(gzPersonnelFoundation.getSalesLevel())){
                gzMonthlySalesCommission.setSalesGear(BigDecimal.ZERO);
            }else {
                gzMonthlySalesCommission.setSalesGear(gzPersonnelFoundation.getSalesLevel());
            }


            gzMonthlySalesCommission.setRatingIevel(gzPersonnelFoundation.getRatingIevel());

            //生成默认状态 待评定
            gzMonthlySalesCommission.setComplete(2);
            gzMonthlySalesCommissions.add(gzMonthlySalesCommission);
        }

        return AjaxResult.success(iGzMonthlySalesCommissionService.saveBatch(gzMonthlySalesCommissions)?1:0);
    }
}
